package txffc

import (
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	jsoniter "github.com/json-iterator/go"
	"github.com/levigross/grequests"

	"gitee.com/goframe/lt-collector/libs/utils"
)

var (
	globalFFC = newTxFFc()

	json = jsoniter.ConfigFastest
)

func CalculateCode() (openCode string, err error) {
	return globalFFC.CalculateCode()
}

func newTxFFc() *TxFFC {
	return &TxFFC{
		apiUrl:        "https://mma.qq.com/cgi-bin/im/online",
		currentOnline: 0,
		checkSeconds:  10,
	}
}

type TxFFC struct {
	//数据来源
	apiUrl string
	//当前在线人数
	currentOnline int64
	//校对数据秒数
	checkSeconds int
}

func (t *TxFFC) CalculateCode() (openCode string, err error) {
	if err = t.request(); err != nil {
		return
	}
	if t.currentOnline == 0 {
		return
	}
	nmString := strconv.Itoa(int(t.currentOnline))
	sl := strings.Split(nmString, "")
	//取万位
	var sum = 0
	for _, v := range sl {
		n, _ := strconv.Atoi(v)
		sum += n
	}
	sumSlice := strings.Split(strconv.Itoa(sum), "")
	w := sumSlice[len(sumSlice)-1]
	//取后4位
	h4 := sl[len(sl)-4:]
	openCode = strings.Join(append([]string{w}, h4...), ",")
	return
}

func (t *TxFFC) request() error {
	type Online struct {
		Current int64 `json:"c"`
		Ec      int64 `json:"ec"`
		History int64 `json:"h"`
	}
	rq := utils.NewRequester()
	rq.SetUrl(t.apiUrl)
	rq.SetRequestFunc(func(rp *grequests.Response) (err error) {
		defer func() {
			if p := recover(); p != nil {
				err = fmt.Errorf("%v", p)
			}
		}()
		str := rp.String()
		jsonStr := regexp.MustCompile(`{([\S\s]*)}`).FindString(str)
		if len(jsonStr) == 0 {
			return errors.New("接口采集失败")
		}
		data := new(Online)
		if err = json.Unmarshal([]byte(jsonStr), data); err != nil {
			return
		}
		if data.Current == 0 {
			return errors.New("在线人数为0")
		}
		if t.currentOnline == data.Current && time.Now().Second() < t.checkSeconds {
			return errors.New("在线人数未刷新")
		}
		t.currentOnline = data.Current
		return
	})
	return rq.Request(utils.GET)
}
